<template>
  <el-dialog
    :visible.sync="visible"
    :close-on-click-modal="false"
    :before-close="beforeClose"
    append-to-body
    top="30px"
    width="1000px"
  >
    <div v-loading="loading">
      <h5 class="section-title">代偿申请表信息</h5>
      <table class="table table-bordered vertical-align-middle text-center table-sm">
        <colgroup>
          <col width="15%" />
          <col width="18%" />
          <col width="15%" />
          <col width="18%" />
          <col width="15%" />
          <col width="19%" />
        </colgroup>
        <tr>
          <td class="td-label">代偿批号</td>
          <td>{{ master.batch_no || '-' }}</td>
          <td class="td-label">提供机构</td>
          <td>{{ bankName }}</td>
          <td class="td-label">申请日期</td>
          <td>{{ finishDate }}</td>
        </tr>
        <tr>
          <td class="td-label">代偿总额</td>
          <td>{{ fundsTotal }} 元</td>
          <td class="td-label">代偿数量</td>
          <td>{{ projectTotal }}</td>
          <td class="td-label">代偿状态</td>
          <td>{{ enumRepayApprovalStatus[master.project_status] || '-' }}</td>
        </tr>
      </table>

      <h5 class="section-title">解保明细表</h5>
      <table class="table table-bordered vertical-align-middle text-center table-sm">
        <colgroup>
          <col width="5%" />
          <col width="12%" />
          <col width="8%" />
          <col width="8%" />
          <col width="10%" />
          <col width="10%" />
          <col width="14%" />
          <col width="10" />
          <col width="10" />
          <col width="10" />
          <!-- <col width="14%"> -->
          <col width="5%" />
        </colgroup>
        <tr>
          <td class="td-label">序号</td>
          <td class="td-label">借款客户</td>
          <td class="td-label">客户类型</td>
          <td class="td-label">
            贷款金额
            <div>(万元)</div>
          </td>
          <td class="td-label">放款日期</td>
          <td class="td-label">到期日期</td>
          <td class="td-label">代偿时间</td>
          <td class="td-label">
            <div>代偿本金</div>
            <div>（元）</div>
          </td>
          <td class="td-label">
            <div>代偿利息</div>
            <div>（元）</div>
          </td>
          <td class="td-label">
            <div>代偿违约金</div>
            <div>（元）</div>
          </td>
          <td class="td-label">操作</td>
        </tr>
        <tr v-for="(p, index) of editData" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ p.customer_name }}</td>
          <td>{{ p.org_class_name }}</td>
          <td>{{ p.warranty_amount }}</td>
          <td>{{ $utils.dateFormat(p.load_date, 'yyyy-MM-dd') }}</td>
          <td>{{ $utils.dateFormat(p.load_end_date, 'yyyy-MM-dd') }}</td>
          <td :class="tdClass">
            <el-date-picker
              v-if="editable"
              type="date"
              class="w-100"
              value-format="yyyy-MM-dd"
              placeholder="代偿时间"
              v-model="p.reach_time"
            ></el-date-picker>
            <span v-else>{{ p.reach_time }}</span>
          </td>
          <td :class="tdClass">
            <el-input
              v-if="editable"
              placeholder="代偿本金"
              v-model="p.principal"
              v-input-number="{ min: 0 }"
            ></el-input>
            <span v-else>{{ p.principal }}</span>
          </td>
          <td :class="tdClass">
            <el-input
              v-if="editable"
              placeholder="代偿利息"
              v-model="p.interest"
              v-input-number="{ min: 0 }"
            ></el-input>
            <span v-else>{{ p.interest }}</span>
          </td>
          <td :class="tdClass">
            <el-input
              v-if="editable"
              placeholder="代偿违约金"
              v-model="p.penalty"
              v-input-number="{ min: 0 }"
            ></el-input>
            <span v-else>{{ p.penalty }}</span>
          </td>
          <td>
            <el-button type="text" @click="handleView(p)">查看</el-button>
          </td>
        </tr>
      </table>

      <h5 class="section-title">附件资料</h5>
      <div class="d-flex" v-if="editable">
        <div class="attach-tag-label">{{ tag }}</div>
        <div>
          <input type="file" ref="uploadInput" @change="changeListener" class="d-none" multiple />
          <el-button
            type="primary"
            size="small"
            class="btn-long mb-1"
            icon="el-icon-upload2"
            @click="handleUpload"
          >
            上传
          </el-button>
          <ul class="list-unstyled">
            <li v-for="(attach, index) in uploadFiles" :key="index" class="attach-item">
              <div>{{ attach.name }}</div>
              <el-button type="text" @click="handleDownloadFile(attach.file)">下载</el-button>
              <el-button type="text" @click="handleDeleteFile(index)">删除</el-button>
            </li>
          </ul>
        </div>
      </div>
      <div v-else>
        <attach-list :attath-data="attachData" :show-label="true"></attach-list>
      </div>
    </div>
    <div class="text-center mt-5" v-if="editable">
      <el-button type="primary" class="btn-long" :loading="saveLoading" @click="handleConfirm">
        提交
      </el-button>
      <el-button class="btn-long" :loading="saveLoading" @click="beforeClose">取消</el-button>
    </div>
    <project-view-dialog
      :visible.sync="viewVisible"
      :batch-no="attachNo"
      :query-id="queryId"
    ></project-view-dialog>
  </el-dialog>
</template>

<script>
import ProjectViewDialog from '@/bank/views/business/limit/new/ProjectViewDialog'
import { mapGetters } from 'vuex'
import { add, downloadByLink } from '@vimi/utils-tool'
import { enumRepayApprovalStatus } from '@/bank/views/limit/postloan/mixins'
import { enumLoanbehStatus } from '@/bank/views/limit/index'
import { uploadOss } from '@/common/api/oss'
import { attachAdapter } from '@/bank/components/attach/index'
import AttachList from '@/bank/components/attach/List'
export default {
  components: {
    ProjectViewDialog,
    AttachList,
  },
  props: {
    visible: Boolean,
    formData: {
      type: Array,
      default: () => {
        return []
      },
    },
    viewMode: { type: Boolean, default: true },
    id: { type: String, default: '' },
  },
  data() {
    return {
      enumLoanbehStatus,
      enumRepayApprovalStatus,
      loading: false,
      saveLoading: false,
      viewVisible: false,
      attachNo: '',
      queryId: '',
      master: {},
      editData: [],
      masterTable: 'un_gua_comps_batch',
      slaveTable: 'un_gua_comps_batch_detail',
      params: {
        subKey: 'datum_one_county_industry.un_gua_comps_batch_id',
      },
      uploadFiles: [],
      attachData: [],
      tag: '代偿附件',
    }
  },
  computed: {
    ...mapGetters(['org', 'user', 'clientId']),
    address() {
      return this.user.queryAddressCode
    },
    bankType() {
      return this.user.clientOrgClassType
    },
    userName() {
      return this.user.realName
    },
    editable() {
      return !this.viewMode
    },
    tdClass() {
      return this.editable ? 'input-td' : ''
    },
    bankName() {
      return this.master.submit_client_name || this.org.orgName
    },
    finishDate() {
      return this.$utils.dateFormat(this.master.create_time || new Date(), 'yyyy-MM-dd')
    },
    fundsTotal() {
      return this.editData.reduce((count, item) => {
        return add(count, item.principal, item.interest, item.penalty)
      }, 0)
    },
    projectTotal() {
      return this.editData.length
    },
  },
  watch: {
    formData: {
      handler: function () {
        this.editData = this.formData.map(item => {
          return { ...item }
        })
      },
      immediate: true,
      deep: true,
    },
    id: {
      handler: function () {
        this.getData()
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    handleDeleteFile(index) {
      this.uploadFiles.splice(index, 1)
    },
    handleDownloadFile(file) {
      const { name, type } = file
      const url = window.URL.createObjectURL(new Blob([file]), { type })
      downloadByLink({ url, filename: name })
      window.URL.revokeObjectURL(url)
    },
    handleUpload() {
      const { uploadInput } = this.$refs
      uploadInput.click()
    },
    changeListener(e) {
      const { files = [] } = e.target

      for (let i = 0; i < files.length; i++) {
        const file = files[i]
        this.uploadFiles.push({
          name: file.name,
          file: file,
        })
      }
      this.handleClear()
    },
    handleClear() {
      const { uploadInput } = this.$refs
      uploadInput.value = ''
    },
    getData() {
      this.editData = []
      if (!this.id) {
        return
      }
      this.params['un_gua_comps_batch_id.eq'] = this.id
      this.loading = true
      Promise.all([
        this.$api.getData(
          this.$serviceName,
          'datum_customer_attachment',
          { 'customer_related_id.eq': this.id },
          { create_time: 'desc' }
        ),
        this.$api.getData(this.$serviceName, this.masterTable, this.params),
      ])
        .then(([attach, res]) => {
          const data = attach?.data ?? []
          const attachData = data.map(attachAdapter)
          this.attachData = [
            {
              tag: this.tag,
              attachs: attachData,
            },
          ]

          this.master = res?.data?.[0] ?? {}
          this.editData = (this.master.datum_one_county_industry || []).map(item => {
            item.reach_time = item.compens_date
            return item
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleConfirm() {
      const masterData = {
        address_code: this.address,
        bank_type: this.bankType,
        submit_client_id: this.clientId,
        submit_client_name: this.bankName,
        submit_person_name: this.userName,
        project_funds: this.fundsTotal,
        project_count: this.projectTotal,
        project_status: 1,
        channel_type: 1,
        is_rural_dev: 0,
      }
      const slaveData = []
      for (let i = 0; i < this.editData.length; i++) {
        const item = this.editData[i]
        if (!item.principal || !item.interest || !item.penalty || !item.reach_time) {
          return this.$message.warning('请输入代偿信息')
        }
        slaveData.push({
          customer_related_id: item.customer_related_id,
          reach_time: item.reach_time,
          principal: item.principal,
          interest: item.interest,
          penalty: item.penalty,
          amount: add(item.principal, item.interest, item.penalty),
        })
      }

      const formData = {
        masterTableInfo: JSON.stringify(masterData),
        masterTableName: this.masterTable,
        slaveTableInfo: JSON.stringify(slaveData),
        slaveTableName: this.slaveTable,
      }

      // 关联添加
      this.saveLoading = true
      this.$api
        .relatedBatch(this.$serviceName, formData)
        .then(res => {
          this.uploadAttach(res.data)
          this.$message.success('提交成功！')
          this.$emit('update:visible', false)
          this.$emit('success', res)
        })
        .catch(err => {
          this.$message.error(err?.data?.error_description || '提交失败，请重试！')
        })
        .finally(() => {
          this.saveLoading = false
        })
    },
    uploadAttach(id) {
      if (!id) {
        return
      }
      const promises = this.uploadFiles.map(it =>
        uploadOss({
          file: it.file,
          dir: `bank/postloan/finish/${id}`,
          type: 1, // 用文件名
          progress: e => (it.percent = e.percent),
        })
      )
      Promise.all(promises)
        .then(list => {
          return this.saveData(list, id)
        })
        .finally(() => {
          this.uploadFiles = []
        })
    },
    saveData(urls, id) {
      if (!urls.length) {
        return Promise.resolve()
      }
      const data = []
      for (let i = 0; i < this.uploadFiles.length; i++) {
        data.push({
          customer_related_id: id,
          attachment_type: this.tag,
          remark: this.uploadFiles[i].name,
          attachment: urls[i],
        })
      }
      return this.$api.addBatch('credit', 'datum_customer_attachment', data)
    },
    handleView(row) {
      this.queryId = row.customer_related_id
      this.attachNo = row.project_approval_batch_bank_id || ''
      this.viewVisible = true
    },
    beforeClose() {
      this.uploadFiles = []
      this.$emit('update:visible', false)
    },
  },
}
</script>
<style lang="scss" scoped>
.section-title {
  font-size: 1.1rem;
  font-weight: bold;
}
.td-label {
  background-color: $gray-100;
}
.vertical-align-middle td {
  vertical-align: middle;
}
.attach-type-item {
  display: flex;
  margin-bottom: 1rem;
  padding-bottom: 1rem;
  border-bottom: 1px dotted $gray-200;
}
.attach-tag-label {
  width: 180px;
  padding-top: 0.25rem;
  padding-left: 0.5rem;
}
.attach-item {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgba(128, 128, 128, 0.1);
}
.input-td {
  background: #ffffee;
}
</style>
